package com.dzt.androidframework.changeskin;

import android.content.res.AssetManager;
import android.content.res.Resources;
import android.view.View;
import android.widget.Toast;

import com.dzt.androidframework.R;
import com.dzt.androidframework.changeskin.lib.SkinManager;
import com.dzt.androidframework.changeskin.lib.callback.ISkinChangingCallback;
import com.dzt.androidframework.changeskin.lib.utils.L;
import com.dzt.androidframework.fragment.FragmentBase;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;

import java.io.File;
import java.lang.reflect.Method;

/**
 * 显示滑出菜单
 */
@ContentView(R.layout.skin_menu)
public class MenuLeftFragment extends FragmentBase {

	@Override
	protected void initWidgets() {
		view.findViewById(R.id.id_changeskin).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SkinManager.getInstance().changeSkin(SkinActivity.mSkinPkgPath,
						SkinActivity.pkgName, new ISkinChangingCallback() {
							@Override
							public void onStart() {
							}

							@Override
							public void onError(Exception e) {
								Toast.makeText(getActivity(), "换肤失败", Toast.LENGTH_SHORT).show();
							}

							@Override
							public void onComplete() {
								Toast.makeText(getActivity(), "换肤成功", Toast.LENGTH_SHORT).show();
							}
						});
			}
		});
	}

	@Event(value = {R.id.id_rl_innerchange01, R.id.id_rl_innerchange02,
			R.id.id_rl_innerchange03, R.id.id_restore, R.id.id_test_resource})
	private void onViewClick(View v) {
		switch (v.getId()) {
			case R.id.id_rl_innerchange01:
				SkinManager.getInstance().changeSkin("red");
				break;
			case R.id.id_rl_innerchange02:
				SkinManager.getInstance().changeSkin("green");
				break;
			case R.id.id_rl_innerchange03:
				SkinManager.getInstance().changeSkin("blue");
				break;
			case R.id.id_restore:
				SkinManager.getInstance().removeAnySkin();
				break;
			case R.id.id_test_resource:
				testResource();
				break;
			default:
				break;
		}
	}

	private void testResource(){
		AssetManager assetManager;
		try {
			assetManager = AssetManager.class.newInstance();
			Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);
			addAssetPath.invoke(assetManager, SkinActivity.mSkinPkgPath);

			File file = new File(SkinActivity.mSkinPkgPath);
			L.e(file.exists() + "");
			Resources superRes = getResources();
			Resources mResources = new Resources(assetManager,
					superRes.getDisplayMetrics(), superRes.getConfiguration());

			int mainBgId = mResources.getIdentifier("skin_main_bg",
					"drawable", SkinActivity.pkgName);
			getActivity().findViewById(R.id.id_drawerLayout)
					.setBackgroundDrawable(mResources.getDrawable(mainBgId));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
